import Taro from '@tarojs/taro'

export default function downLoad(imagePath, type = 'image', isTmp = false) {
  let len = 1
  if (imagePath instanceof Array) {
    len = imagePath.length
  }
  console.log('imagePath', imagePath)
  Taro.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        Taro.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            getImgInfo(1)
          },
          fail: () => {
            Taro.showModal({
              title: '授权',
              content: '您拒绝了授权请求，是否要手动开启？',
              success: (res) => {
                if (res.confirm) {
                  Taro.openSetting({
                    success: (res) => {
                      res.authSetting = {
                        "scope.writePhotosAlbum": true,
                      }
                    }
                  })
                } else if (res.cancel) {
                  Taro.showToast({
                    title: '保存失败！',
                    icon: 'close',
                    duration: 2000
                  })
                }
              }
            })
          }
        })
      } else {
        getImgInfo(1)
      }
    }
  })

  const getImgInfo = (num) => {
    /* 我这里要保存多张图片，一张的话就可以取消这些，具体看你的需求 */
    if (num > len) {
      return false;
    }
    Taro.showToast({
      title: `下载中${num}/${len}`,
      icon: 'loading'
    })


    if (isTmp) {
      saveMethod(len > 1 ? imagePath[num - 1].url : imagePath, num)
      setTimeout(() => {
        if (num + 1 <= len) {
          num++;
          getImgInfo(num);
        }
      }, 50)
      return;
    }

    /* 获取图片信息 */
    // getImageInfo
    Taro.downloadFile({
      // HOST+item.video.staticFilePath
      // url: len > 1?HOST + imagePath[num-1].staticFilePath:imagePath,
      url: len > 1 ? imagePath[num - 1].url : imagePath,
      success: (image) => {
        saveMethod(image, num)
      },
      fail: (err) => {
        Taro.showToast({title: '保存失败' + err.errMsg, icon: 'none', duration: 3000})
      }
    });
    setTimeout(() => {
      if (num + 1 <= len) {
        num++;
        getImgInfo(num);
      }
    }, 50)
  }


  const saveMethod = (image, num) => {
    console.log('image', image);
    /* 保存图片到相册 */
    // saveImageToPhotosAlbum
    // saveVideoToPhotosAlbum

    if (type == 'image') {
      Taro.saveImageToPhotosAlbum({
        // filePath: image.path
        filePath: isTmp ? image : image.tempFilePath
      }).then(res => {
        // if(len > 1  && num > 1){
        //   Taro.hideToast()
        // }
        console.log('num', num)
        console.log('len', len)

        Taro.showToast({
          title: `下载中${num}/${len}`,
          icon: 'loading'
        }).then(_ => {
          if (num === len) {
            Taro.showModal({
              title: '保存成功',
              content: '图片已成功保存到相册，快去分享到您的圈子吧',
              showCancel: false,
              success: (result) => {
                if (result['confirm'] === true) {
                  console.log('点击了确定按钮', '')
                }
              }
            })
            // Taro.showToast({
            //   title: '图片保存成功'
            // })
          }
        })

      }).catch(err => {
        console.log('err', err)
        Taro.showToast({title: '图片保存失败' + err.errMsg, icon: 'none', duration: 3000})
        Taro.hideLoading()
      }).finally(_ => {
        Taro.hideLoading()
      })
    } else {
      Taro.saveVideoToPhotosAlbum({
        filePath: image.tempFilePath
      }).then(res => {
        if (len > 1 && num > 1) {
          Taro.hideToast()
        }
        Taro.showToast({
          title: `下载中${num}/${len}`,
          icon: 'loading'
        }).then(_ => {
          if (num === len) {
            Taro.showModal({
              title: '保存成功',
              content: '视频已成功保存到相册，快去分享到您的圈子吧',
              showCancel: false
            })
            // Taro.showToast({
            //   title: '图片保存成功'
            // })
          }
        })
      }).catch(err => {
        console.log('视频保存失败', err)
        Taro.showToast({title: '视频保存失败' + err.errMsg, icon: 'none'})
        Taro.hideLoading()
      }).finally(_ => {
        Taro.hideLoading()
      })
    }
  }

}
